﻿using System;
using Microsoft.SharePoint;

namespace RoketSolutions.SP2010.Infrostructure.Data.Repositories.Helpers
{
    public sealed class ListResolver : IDisposable
    {
        private readonly String siteUrl;
        private readonly String listName;
        private readonly bool needDispose;
        private SPList list;
        private SPSite site;
        private SPWeb web;

        public ListResolver(String siteUrl, string listName)
        {
            this.siteUrl = siteUrl;
            this.listName = listName;
            needDispose = true;
        }

        public ListResolver(SPWeb web, string listName)
        {
            this.web = web;
            this.listName = listName;
            needDispose = false;
        }

        public SPList List
        {
            get
            {
                if (list == null)
                {
                    if (web == null)
                    {
                        site = new SPSite(siteUrl);
                        web = site.OpenWeb();
                    }
                    list = web.Lists[listName];
                }
                return list;
            }
        }

        public void Dispose()
        {
            if (!needDispose)
                return;

            if (web != null)
                web.Dispose();

            if (site != null)
                site.Dispose();
        }
    }

}